package com.khstudio.videocapture.khvideocapture;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.khstudio.api.util.KhLog;
import com.khstudio.api.view.VideoPlayButton_Kh;
import com.khstudio.api.view.VideoPlayButton_Kh.VideoPlayButtonClickListener;
import com.khstudio.videocapture.R;
import com.khstudio.videocapture.view.VideoFadeLayout_Kh;
import com.khstudio.videocapture.view.VideoPlayerView_Kh;
import com.khstudio.videocapture.view.VideoPlayerView_Kh.OnVideoPlayerErrorListener;
import com.khstudio.videocapture.view.VideoPlayerView_Kh.OnVideoPlayerGetFrameListener;
import com.khstudio.videocapture.view.VideoPlayerView_Kh.OnVideoPlayerPlayListener;
import com.khstudio.videocapture.view.VideoPlayerView_Kh.OnVideoPlayerPrepareListener;
import com.khstudio.videocapture.view.VideoPlayerView_Kh.OnVideoPlayerReleaseListener;
import com.khstudio.videocapture.view.VideoPlayerView_Kh.OnVideoPlayerSeekListener;
import com.khstudio.videocapture.view.VideoSeekBarLayout_Kh;
import com.khstudio.videocapture.view.VideoSeekBarLayout_Kh.VideoSeekBarLayoutListener_Kh;

public class KhVideoCaptureFragment extends Fragment {
    private static final int MSG_PLAY_PROGRESS = 0x0001;

//    private KhVideoCaptureControlGroup  mControl;
    private VideoPlayerView_Kh          mPlayerView;
    private VideoFadeLayout_Kh          mVideoFadeLayout;
    private VideoSeekBarLayout_Kh       mVideoSeekBarLayout;

    private ImageView                   mImageView;

    private long                        mCTime;
    private long                        mProgressDelay = 0;

    private KhVideoCaptureFragmentListener mListener;

    public interface KhVideoCaptureFragmentListener {

    }

    public static KhVideoCaptureFragment newInstance(String path) {
        KhVideoCaptureFragment f = new KhVideoCaptureFragment();

        Bundle args = new Bundle();
        args.putString("KhPath", path);
        f.setArguments(args);

        return f;
    }

    public void setonKhDualListFragmentListener(KhVideoCaptureFragmentListener l) {
        mListener = l;
    }

    public void back() {

    }

    public void setDataSource(String s) {
        mPlayerView.setDataSource(s);
        mPlayerView.prepare(new OnVideoPlayerPrepareListener() {
            @Override
            public void onPrepare() {
                mPlayerView.seek(0);
                mVideoSeekBarLayout.setDuration(mPlayerView.getDurationMs());
            }
        });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        KhLog.v("KhVideoCaptureFragment : onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KhLog.i("KhVideoCaptureFragment : onCreate");

        mListener = null;
        mCTime = 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        KhLog.i("KhVideoCaptureFragment : onCreateView "+container);

        View v = inflater.inflate(R.layout.kh_videocapture, container, false);

        _initVideoPlayer(v);
        _initVideoFadeLayout(v);

        mImageView = (ImageView) v.findViewById(R.id.kh_videocapture_imageview);

        if (savedInstanceState != null) {
            mCTime = savedInstanceState.getLong("KhCTime");
            KhLog.e("seek 2 KhVideoCaptureFragment KhCTime = %d", mCTime);
//            mPlayerView.seek(mCTime);
//            mControl.setSeekBarThumbTimeForce(mCTime);
//            mControl.set
        } else {
            KhLog.e("seek 3 ");
//            mPlayerView.seek(0);
        }

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        KhLog.v("KhVideoCaptureFragment : onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        KhLog.v("KhVideoCaptureFragment : onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        KhLog.v("KhVideoCaptureFragment : onResume");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putLong("KhCTime", mCTime);

        super.onSaveInstanceState(outState);
        KhLog.v("KhVideoCaptureFragment : onSaveInstanceState");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        KhLog.v("KhVideoCaptureFragment : onConfigurationChanged");
    }

    @Override
    public void onPause() {
        KhLog.v("KhVideoCaptureFragment : onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        KhLog.v("KhVideoCaptureFragment : onStop");
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        KhLog.v("KhVideoCaptureFragment : onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        KhLog.v("KhVideoCaptureFragment : onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        KhLog.v("KhVideoCaptureFragment : onDestroy");
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        KhLog.v("KhVideoCaptureFragment : onDetach");
        super.onDetach();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    private void _initVideoPlayer(View container) {
        mPlayerView = (VideoPlayerView_Kh) container.findViewById(R.id.kh_videocapture_player);

        mPlayerView.setOnVideoPlayerSeekListener(new OnVideoPlayerSeekListener() {

            @Override
            public void onSeek() {
                KhLog.i("KhVideoCaptureFragment : onSeek");
                mImageView.setVisibility(View.GONE);
                mVideoFadeLayout.setGroupEnabled(true);
                if(mPlayerView.isPlay()) {
                    mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
                }
            }
        });

        mPlayerView.setOnVideoPlayerPlayListener(new OnVideoPlayerPlayListener() {

            @Override
            public void onPlay(boolean eos) {
                KhLog.i("KhVideoCaptureFragment : onPlay");
                mImageView.setVisibility(View.GONE);
                mHandler.removeMessages(MSG_PLAY_PROGRESS);
            }
        });

        mPlayerView.setOnVideoPlayerGetFrameListener(new OnVideoPlayerGetFrameListener() {

            @Override
            public void onGetFrame(Bitmap frame, boolean isLast) {
                KhLog.i("KhVideoCaptureFragment : onGetFrame "+frame.toString());
                mImageView.setImageBitmap(frame);
                mImageView.setVisibility(View.VISIBLE);
                if(isLast) {
                    mVideoFadeLayout.setGroupEnabled(true);
                }
            }
        });

        mPlayerView.setOnVideoPlayerErrorListener(new OnVideoPlayerErrorListener() {

            @Override
            public void onError(int what, int extra) {
                KhLog.i("KhVideoCaptureFragment : onError what = %d extra = %d", what, extra);
            }
        });

        mPlayerView.setOnVideoPlayerReleaseListener(new OnVideoPlayerReleaseListener() {

            @Override
            public void onRelease() {
                KhLog.i("KhVideoCaptureFragment : onRelease");
            }
        });

    }

    private void _initVideoFadeLayout(View container) {
        mVideoFadeLayout = (VideoFadeLayout_Kh) container.findViewById(R.id.kh_videocapture_showhide_group);
        View v = null;

        LinearLayout leftLayout = new LinearLayout(getActivity());
        leftLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        leftLayout.setOrientation(LinearLayout.VERTICAL);

        v = new ImageButton(getActivity());
        v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        v.setPadding(0, 0, 0, 0);
        v.setEnabled(false);
        v.setVisibility(View.VISIBLE);
        v.setBackgroundColor(Color.TRANSPARENT);
        v.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mVideoFadeLayout.getGroupEnabled()) {
                    mVideoFadeLayout.setGroupEnabled(false);
                } else {
                    mVideoFadeLayout.setGroupEnabled(true);
                }
            }
        });
        ((ImageButton) v).setImageResource(R.drawable.kh_videocapture_control_btn_save_single);
        leftLayout.addView(v);

        v = new ImageButton(getActivity());
        v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        v.setPadding(0, 0, 0, 0);
        v.setEnabled(false);
        v.setVisibility(View.VISIBLE);
        v.setBackgroundColor(Color.TRANSPARENT);
        ((ImageButton) v).setImageResource(R.drawable.kh_videocapture_control_btn_save_multi);
        leftLayout.addView(v);

//        v = new KhVideoSeekBarLayout(getActivity());
//        leftLayout.addView(v);

        mVideoFadeLayout.setRightView(leftLayout);

//        v = new SeekBarViewDemo(getActivity());
//        v.setVisibility(View.VISIBLE);
//        ((SeekBarViewDemo) v).setDuration(100000);

        mVideoSeekBarLayout = new VideoSeekBarLayout_Kh(getActivity());
        mVideoSeekBarLayout.setOnVideoSeekBarLayoutListener(new VideoSeekBarLayoutListener_Kh() {
            @Override
            public void onChangeThumb(long c) {
                KhLog.i("onChangeThumb %d", c);
                mHandler.removeMessages(MSG_PLAY_PROGRESS);
                mPlayerView.seek(c);
            }
        });

        mVideoFadeLayout.setBottomView(mVideoSeekBarLayout);

        v = new VideoPlayButton_Kh(getActivity());
        v.setEnabled(true);
        v.setVisibility(View.VISIBLE);
        ((VideoPlayButton_Kh) v).setOnVideoPlayButtonClickListener(new VideoPlayButtonClickListener() {
            @Override
            public void onClickListener(int s) {
                if(s == VideoPlayButton_Kh.PLAY) {
                    mPlayerView.play();
                    mProgressDelay = mVideoSeekBarLayout.getUnitMs();
                    mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
                } else if(s == VideoPlayButton_Kh.PAUSE) {
                    mPlayerView.stop();
                }
            }
        });
        ((VideoPlayButton_Kh) v).setDrawableOnId(R.drawable.kh_videocapture_control_btn_play);
        ((VideoPlayButton_Kh) v).setDrawableOffId(R.drawable.kh_videocapture_control_btn_pause);

        mVideoFadeLayout.setCenterView(v);

    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case MSG_PLAY_PROGRESS : {
//                    mControl.setSeekBarThumbTime(mPlayerView.getCurrentTimeMs());
                    mVideoSeekBarLayout.setPlayTimeMs(mPlayerView.getCurrentTimeMs());
                    if(mPlayerView.isPlay())
                        mHandler.sendEmptyMessageDelayed(MSG_PLAY_PROGRESS, mProgressDelay);
                }
                break;
            }
        }
    };

    private OnClickListener SaveSingleFrameListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            KhLog.i("onClick : Save Frame - single");
            if (mPlayerView.getRotation() == 0) {
                mPlayerView.setRotation(90);
            } else if(mPlayerView.getRotation() == 90) {
                mPlayerView.setRotation(180);
            } else if(mPlayerView.getRotation() == 180) {
                mPlayerView.setRotation(270);
            } else {
                mPlayerView.setRotation(0);
            }
        }
    };

    private OnClickListener SaveMultiFrameListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            KhLog.i("onClick : Save Frame - multi getFrameList = %d",mPlayerView.getDurationMs());
//            mPlayerView.getFrame(mPlayerView.getCurrentTimeMs());
            mPlayerView.getFrameList(0, mPlayerView.getDurationMs(), 11);
//            mControl.setGroupEnabled(false);
        }
    };

    private OnClickListener RepositoryListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            KhLog.i("onClick : Repository");
        }
    };
}
